<?php
namespace admin\service;

/**--tmpl-use--**/
use herosphp\core\Loader;
use herosphp\core\WebApplication;

/**--tmpl-import--**/
class SettingService extends CommonService
{

    private $thisModel = null;

    public function __construct($model)
    {
        parent::__construct($model);

        $this->thisModel = Loader::model('adminSetting');
    }

    //获取所有app的某项配置
    public function getAllAppSetting($item)
    {
        $this->thisModel->disableAppFilter();
        $all = $this->thisModel->getItems(array('name' => $item));
        $this->thisModel->enableAppFilter();
        return $all;

    }
    /**--tmpl-method--**/
    /*
* 根据配置项数组获取配置数组
* @param 配置项数组
* @return : array 配置数组
 */
    public function getSettings($arr)
    {

        $app = WebApplication::getInstance();
        $appConfig = $app->getConfigs();
        $allConfigs = $this->getConfigs();
        $result = array();
        foreach ($arr as $k) {
            if (isset($allConfigs[$k])) {
                $result[$k] = $allConfigs[$k];
            } else if (isset($appConfig[$k])) {
                $result[$k] = $appConfig[$k];
            }
        }

        return $result;

    }

    /*
     * 获取配置项的值
     * @param $config 配置
     * @return : mixed 配置值
     */
    public function getSetting($config)
    {
        $allConfigs = $this->getConfigs();
        foreach ($allConfigs as $k => $v) {
            if ($k == $config) {
                return $v;
            }
        }
        $app = WebApplication::getInstance();
        $appConfig = $app->getConfigs();
        if (isset($appConfig[$config])) {
            return $appConfig[$config];
        }
        return false;
    }

    /*
     * 修改配置
     * @param $configs : 配置信息
     * @return
     */

    public function setConfigs($configs)
    {


        $allConfigs = $this->getConfigs();

        $configKeys = array_keys($allConfigs);
        foreach ($configs as $k => $v) {
            if (in_array($k, $configKeys)) {
                if ($v != $allConfigs[$k]) {
                    parent::updates(array('value' => $v), array('name' => $k, 'app_id' => appId()));
                }
            } else {
                $array = array(
                    'name' => $k,
                    'value' => $v,
                );
                parent::add($array);
            }
        }
        return true;
    }


    public function deleteConfigs($configs)
    {

        $allConfigs = $this->getConfigs();

        $configKeys = array_keys($allConfigs);
        foreach ($configs as $v) {
            if (in_array($v, $configKeys)) {
                parent::deletes(array('name' => $v));
            }
        }
        return true;
    }

    public function getConfigId($item)
    {
        $d = parent::getItem(array('name' => $item));
        if ($d) {
            return $d['id'];
        }
        return 0;
    }

    public function getQqStr($count = 1, $type = 0, $space = '&nbsp;')
    {
        $arr = $this->getQa($count);
        $rs = '';
        foreach ($arr as $k => $v) {

            if ($type == 0) {
                $rs .= $v['qq'] . $space;
            } else {

                $rs .= $v['name'] . ':' . $v['qq'] . $space;
            }

        }
        return trim($rs, $space);
    }

    public function getQa($count = 1)
    {

        $qq = $this->getSetting('cs_qq');
        $arr = json_decode($qq, true);
        return array_slice($arr, 0, $count);
    }

    /*
    * 获取工作时间字符串
    * @param $space : 行内分隔符
    * @param $enter : 换行符
     */
    public function getWorktimeStr($space = '&nbsp;', $enter = '<br/>')
    {
        $worktimeConfig = $this->getSetting('cs_work_time');
        $arr = json_decode($worktimeConfig, true);
        $map = array('', '一', '二', '三', '四', '五', '六', '日');
        $str = '';
        foreach ($arr as $v) {
            if ($v['worktime_enabled']) {
                if ($v['startday'] == $v['endday']) {
                    $str .= "周{$map[$v['endday']]}{$space}{$v['starttime']}-{$v['endtime']}{$enter}";
                } else {
                    $str .= "周{$map[$v['startday']]}至周{$map[$v['endday']]}{$space}{$v['starttime']}-{$v['endtime']}{$enter}";
                }
            }
        }
        return trim($str, $enter);

    }

    /*
    * 判断给定时间是否是工作时间
    * @param $time : date or timestamp 要判断的时间，默认为false 即判断当前时间
     */
    public function isWrokTime($time = false)
    {
        if ($time == false) {
            $time = time();
        }
        if (!is_numeric($time)) {
            $time = strtotime($time);
        }
        $worktimeConfig = $this->getSetting('cs_work_time');
        $arr = json_decode($worktimeConfig, true);
        $w = date('w', $time);
        $m = intval(date('Hi', $time));
        $w = $w ? $w : 7;
        foreach ($arr as $v) {
            if ($v['worktime_enabled']) {
                if ($w >= intval($v['startday']) && $w <= intval($v['endday']) && $m >= intval(str_replace(':', '', $v['starttime'])) && $m <= intval(str_replace(':', '', $v['endtime']))) {
                    return true;
                }
            }
        }
        return false;

    }

    /*
     * 判断给定内容是否包含违禁词
     * @param $content string : 要判断的内容
     * @param $words array : 违禁词数组 默认为空，表示从系统设置中获取
     */

    public function hasDenyWord($content, $words = array())
    {
        if (empty($words)) {
            $denyWords = $this->getSetting('prohibitedWords');
            $words = explode(',', $denyWords);
        }
        $skip = array(
            ' ', ' '
        );
        $contentLen = mb_strlen($content);

        $matchStruct = array();
        foreach ($words as $v) {
            $matchStruct[] = array( //匹配队列
                'word' => $v,
                'ind' => 0,        //匹配指针
                'len' => mb_strlen($v),
            );
        }
        for ($i = 0 /* 行走指针 */; $i < $contentLen; $i++) {
            $currCh = mb_substr($content, $i, 1);
            if (!in_array($currCh, $skip)) {
                foreach ($matchStruct as $kk => $vv) {
                    $mCh = mb_substr($vv['word'], $vv['ind'], 1);
                    if ($mCh == $currCh) {
                        $matchStruct[$kk]['ind']++;
                        if ($matchStruct[$kk]['ind'] == $vv['len']) {
                            return $vv['word'];
                        } else {
                            $tmp = $vv;
                            $tmp['ind'] = 0;
                            $matchStruct[] = $tmp;

                        }
                    } else {
                        if ($vv['ind'] != 0) {
                            unset($matchStruct[$kk]);
                        }
                    }
                }
            }
        }
        return false;
    }

    public function getSmsConfig()
    {

        $smsConfig = $this->getSettings(array('sms_open', 'sms_provider', 'sms_account', 'sms_password', 'sms_key', 'sms_sign', 'sms_test_content'));

        return $smsConfig;
    }
}
	
